/**
 * Copyright &copy; 2012-2016 <a href="https://istep.lczyfz.com">Istep</a> All rights reserved.
 */
package com.lczyfz.istep.modules.teach.web;

import com.google.common.collect.Lists;
import com.lczyfz.istep.common.beanvalidator.BeanValidators;
import com.lczyfz.istep.common.config.Global;
import com.lczyfz.istep.common.constants.StuWithNoClassFlag;
import com.lczyfz.istep.common.persistence.Page;
import com.lczyfz.istep.common.utils.JsonModel;
import com.lczyfz.istep.common.utils.StringUtils;
import com.lczyfz.istep.common.utils.excel.ExportExcel;
import com.lczyfz.istep.common.utils.excel.ImportExcel;
import com.lczyfz.istep.common.web.BaseController;
import com.lczyfz.istep.modules.sys.dao.RoleDao;
import com.lczyfz.istep.modules.sys.entity.Role;
import com.lczyfz.istep.modules.sys.entity.User;
import com.lczyfz.istep.modules.sys.service.SystemService;
import com.lczyfz.istep.modules.sys.utils.UserUtils;
import com.lczyfz.istep.modules.teach.entity.TeachClass;
import com.lczyfz.istep.modules.teach.entity.TeachStudent;
import com.lczyfz.istep.modules.teach.service.TeachClassService;
import com.lczyfz.istep.modules.teach.service.TeachStudentService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 学生管理Controller
 * @author cqh
 * @version 2017-01-14
 */
@Controller
@RequestMapping(value = "${adminPath}/teach/teachStudent")
public class TeachStudentController extends BaseController {

	@Autowired
	private TeachStudentService teachStudentService;
	@Autowired
	private TeachClassService teachClassService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private RoleDao roleDao;
	
	@ModelAttribute
	public TeachStudent get(@RequestParam(required=false) String id) {
		TeachStudent entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = teachStudentService.get(id);
		}
		if (entity == null){
			entity = new TeachStudent();
		}
		return entity;
	}

	//学生管理列表展示
	@RequiresPermissions("teach:teachStudent:view")
	@RequestMapping(value = {"list", ""})
	public String list(TeachStudent teachStudent, HttpServletRequest request, HttpServletResponse response, Model model) {
		logger.debug("=Evan==teachStudent=="+teachStudent);
		Page<TeachStudent> page = teachStudentService.findPage(new Page<TeachStudent>(request, response), teachStudent);
		//条件查询下拉框
		List<TeachClass> allClassList = teachStudentService.findAllClassList();
		model.addAttribute("allClassList", allClassList);
		model.addAttribute("page", page);
		return "modules/teach/teachStudentList";
	}

	//根据学生id找到所属的多个班级
	@ResponseBody
	@RequestMapping(value = "viewBelongClass")
	public List<TeachClass> viewBelongClass(String userId){
		logger.debug("dingh===aaa=="+teachClassService.findBelongClassById(userId).size());
		return teachClassService.findBelongClassById(userId);
	}

	//AlisaYe
	//班级管理-->详情-->学生列表-->学生管理
//	@RequiresPermissions("teach:teachStudent:view")
//	@RequestMapping(value = {"list", ""})
//	public String list(TeachStudent teachStudent, HttpServletRequest request, HttpServletResponse response, Model model) {
//		String getClassName;
//		logger.debug("=Evan==teachStudent=="+teachStudent);
//		Page<TeachStudent> page = teachStudentService.findPage(new Page<TeachStudent>(request, response), teachStudent);
//		for(int i=0;i<page.getList().size();i++){
//			if(page.getList().get(i).getClassId().equals("0")){
//				getClassName="";
//			}else {
//				TeachClass teachclass = teachClassService.get(page.getList().get(i).getClassId());
//				logger.debug("=Evan==getClassId=="+page.getList().get(i).getClassId());
//				getClassName = teachclass.getClassName();
//			}
//			page.getList().get(i).setClassId(getClassName);
//		}
//		//条件查询下拉框
//		List<TeachClass> allClassList = teachStudentService.findAllClassList();
//		model.addAttribute("allClassList", allClassList);
//		model.addAttribute("page", page);
//		return "modules/teach/teachStudentList";
//	}



	//学生管理添加页面跳转
	@RequiresPermissions("teach:teachStudent:view")
	@RequestMapping(value = "form")
	public String form(TeachStudent teachStudent, Model model) {
		List<TeachClass> allClassList = teachStudentService.findAllClassList();
		model.addAttribute("allClassList", allClassList);
		model.addAttribute("teachStudent", teachStudent);
		return "modules/teach/teachStudentForm";
	}

	//学生管理-添加
	@RequiresPermissions("teach:teachStudent:edit")
	@RequestMapping(value = "save")
	public String save(TeachStudent teachStudent, Model model, RedirectAttributes redirectAttributes) {
		logger.debug("=Evan===save之前==="+teachStudent.getPassword()+","+teachStudent.getNewPassword());
		// 如果新密码不为空，则更换密码
		if (StringUtils.isNotBlank(teachStudent.getNewPassword())) {
			teachStudent.setPassword(SystemService.entryptPassword(teachStudent.getNewPassword()));
		}
		logger.debug("=Evan===save之后==="+teachStudent.getPassword()+","+teachStudent.getNewPassword());

		if (!beanValidator(model, teachStudent)){
			return form(teachStudent, model);
		}
		if ("false".equals(checkLoginName(teachStudent.getOldLoginName(), teachStudent.getLoginName()))) {
			addMessage(model, "保存学生'" + teachStudent.getLoginName() + "'失败，登录名已存在");
			return form(teachStudent, model);
		}

		// 角色数据有效性验证，过滤不在授权内的角色
		List<Role> roleList = Lists.newArrayList();
		Role role  =new Role();
		role.setOffice(null);
		Role StudentRoleId = roleDao.findStudentRole(new Role());
		logger.debug("=Evan==StudentRoleId==" +StudentRoleId);
		roleList.add(StudentRoleId);

//		List<Role> roleList2 = systemService.findAllRole();
//		logger.debug("=Evan==roleList2==" +roleList2);
//
//		for (Role r : systemService.findAllRole()) {
//			if (StudentRoleId.contains(r.getId())) {
//				roleList.add(r);
//			}
//		}
		teachStudent.setRoleList(roleList);

		User user = new User();
		user.setId(teachStudent.getId());
		user.setCompany(null);
		user.setOffice(null);
		user.setLoginName(teachStudent.getLoginName());
		user.setPassword(teachStudent.getPassword());
		user.setNo(teachStudent.getNo());
		user.setName(teachStudent.getName());
		user.setEmail(teachStudent.getEmail());
		user.setPhone(teachStudent.getPhone());
		user.setMobile(teachStudent.getMobile());
		user.setUserType(teachStudent.getUserType());
		user.setLoginIp(teachStudent.getLoginIp());
		user.setLoginDate(teachStudent.getLoginDate());
		user.setLoginFlag(teachStudent.getLoginFlag());
		user.setPhoto(teachStudent.getPhoto());

		user.setOldLoginName(teachStudent.getOldLoginName());
		user.setNewPassword(teachStudent.getNewPassword());

		user.setOldLoginIp(teachStudent.getLoginIp());
		user.setOldLoginDate(teachStudent.getLoginDate());

		user.setRole(teachStudent.getRole());
		user.setRoleList(teachStudent.getRoleList());

		systemService.saveUser(user);
		if(user.getId()!=null&&teachStudent!=null&&teachStudent.getClassId()!=null)
		{
			teachStudentService.studentInsertClassStudent(user.getId(),teachStudent.getClassId());
		}

//		teachStudentService.saveStudent(teachStudent);

		// 清除当前用户缓存
		if (teachStudent.getLoginName().equals(UserUtils.getUser().getLoginName())) {
			UserUtils.clearCache();
			//UserUtils.getCacheMap().clear();
		}
		addMessage(redirectAttributes, "保存学生'" + teachStudent.getLoginName() + "'成功");
		return "redirect:"+Global.getAdminPath()+"/teach/teachStudent/list/?repage";
	}



	//学生管理-删除
	@RequiresPermissions("teach:teachStudent:edit")
	@RequestMapping(value = "delete")
	public String delete(TeachStudent teachStudent, RedirectAttributes redirectAttributes) {
		teachStudentService.delete(teachStudent);
		addMessage(redirectAttributes, "删除学生'" + teachStudent.getLoginName() + "'成功");
		return "redirect:"+Global.getAdminPath()+"/teach/teachStudent/?repage";
	}

	//批量添加到班级-页面跳转
	@RequestMapping(value = "batchAddForm")
	public String batchAddForm(Model model,TeachStudent teachStudent) {
		List<TeachClass> allClassList = teachStudentService.findAllClassList();
		List<TeachStudent> allBatchAddStudentList = teachStudentService.findList(teachStudent);
		model.addAttribute("allClassList", allClassList);
		model.addAttribute("allBatchAddStudentList", allBatchAddStudentList);
		return "modules/teach/teachBatchAddForm";
	}

	//批量添加到班级-根据班级id联动获取不在该班级内的学生
	@ResponseBody
	@RequestMapping(value = "findStudentByClassId")
	public JsonModel findStudentByClassId(@RequestParam(required = false) String classId) {
		JsonModel jsonModel = new JsonModel();
		Map<String,List> map = new HashMap<>();
		map.put("StudentList",teachStudentService.findBatchAddStudentByClassId(classId));
		jsonModel.setDataObj(map);
		return jsonModel;
	}

	//批量添加到班级-添加
	@RequestMapping(value = "batchAdd")
	public String batchAdd(String classId, String duallist, RedirectAttributes redirectAttributes) {
		logger.debug("=Evan==duallist=="+duallist);
		String[] allBatchAddStudentList = duallist.split(",");
		for (String anAllBatchAddStudentList : allBatchAddStudentList) {
			teachStudentService.studentInsertClassStudent(anAllBatchAddStudentList, classId);
		}
		addMessage(redirectAttributes, "批量添加到班级成功");
		return "redirect:" + Global.getAdminPath() + "/teach/teachStudent/?repage";
	}

	/**
	 * 下载导入学生数据模板
	 *
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "学生数据导入模板.xlsx";
			List<TeachStudent> list = Lists.newArrayList();
			TeachStudent teachStudent = teachStudentService.get(UserUtils.getUser().getId());
			teachStudent.setClassId("XXX名称");
			list.add(teachStudent);
			logger.debug("=Evan==学生数据导入模板==" +list);
			new ExportExcel("学生数据", TeachStudent.class, 2).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/teach/teachStudent/list/?repage";
	}

	/**
	 * 导入学生数据
	 *
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "import", method = RequestMethod.POST)
	public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<TeachStudent> list = ei.getDataList(TeachStudent.class);
			logger.debug("=Evan==importFile==" +list);

			for (TeachStudent teachStudent : list) {
				try {
					if(teachStudent.getClassId()==null || teachStudent.getClassId().equals("")){

						if("true".equals(checkLoginName("", teachStudent.getLoginName()))){
							//设置导入学生初始密码为：123456
							teachStudent.setPassword(SystemService.entryptPassword("123456"));
							BeanValidators.validateWithException(validator, teachStudent);
							//若该学生在添加时（包括通过Excel进行添加）时，班级为无，则默认该学生的班级id为： 0
							teachStudentService.saveStudentByExcel(teachStudent, StuWithNoClassFlag.stuWithNoClassFlag);
							successNum++;
						} else {
							failureMsg.append("<br/>登录名: ").append(teachStudent.getLoginName()).append(" 已存在; ");
							failureNum++;
						}
					} else {
						if(!"false".equals(checkClassName(teachStudent.getClassId()))){
							if("true".equals(checkLoginName("", teachStudent.getLoginName()))) {
								//设置导入学生初始密码为：123456
								teachStudent.setPassword(SystemService.entryptPassword("123456"));
								BeanValidators.validateWithException(validator, teachStudent);
								teachStudentService.saveStudentByExcel(teachStudent, checkClassName(teachStudent.getClassId()));
								successNum++;
							} else {
								failureMsg.append("<br/>登录名: ").append(teachStudent.getLoginName()).append(" 已存在; ");
								failureNum++;
							}
						}else {
							failureMsg.append("<br/>班级名称: ").append(teachStudent.getClassId()).append(" 不存在; ");
							failureNum++;
						}
					}
				} catch (ConstraintViolationException ex) {
					failureMsg.append("<br/>登录名: ").append(teachStudent.getLoginName()).append(" 导入失败：");
					List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
					for (String message : messageList) {
						failureMsg.append(message).append("; ");
						failureNum++;
					}
				} catch (Exception ex) {
					failureMsg.append("<br/>2登录名: ").append(teachStudent.getLoginName()).append(" 导入失败：").append(ex.getMessage());
				}
			}
			if (failureNum > 0) {
				failureMsg.insert(0, "，失败 " + failureNum + " 条用户，导入信息如下：");
			}
			addMessage(redirectAttributes, "已成功导入 " + successNum + " 条用户" + failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入用户失败！失败信息：" + e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/teach/teachStudent/list/?repage";
	}

	//验证导入班级名称是否有效,false时，说明班级名不存在
	@ResponseBody
	@RequiresPermissions("teach:teachStudent:edit")
	@RequestMapping(value = "checkClassName")
	public String checkClassName(String oldClassName) {
		List<TeachClass> allClassList = teachStudentService.findAllClassList();
		for (TeachClass anAllClassList : allClassList) {
			if (oldClassName.equals(anAllClassList.getClassName())) {
				return anAllClassList.getId();
			}
		}
		return "false";
	}

	//验证导入登录名称是否有效,false时，说明登录名已经存在
	@ResponseBody
	@RequiresPermissions("teach:teachStudent:edit")
	@RequestMapping(value = "checkLoginName")
	public String checkLoginName(String oldLoginName,String loginName) {
		if (loginName != null && loginName.equals(oldLoginName)) {
			logger.debug("=Evan===修改学生==="+oldLoginName+","+loginName);
			return "true";
		} else if(loginName != null && teachStudentService.findStudentByLoginName(loginName) == null){
			logger.debug("=Evan===添加学生==="+oldLoginName+","+loginName);
			return "true";
		}
		return "false";
	}




}